import React, { useState, useEffect } from 'react'
import { PlusOutlined } from '@ant-design/icons'
import {
  Space,
  Table,
  Tag,
  Button,
  Modal,
  Form,
  Input,
  Radio,
  Upload,
  Select,
  message,
  Pagination,
  Popconfirm
} from 'antd'
import './index.modules.scss'
import { baseURL } from '@/http/request'
import { appList } from '@/http/api/login'
import { userList, useradminadd, userdelete } from '@/http/api/user'
import { numberList } from '@/http/api/number'

let pageData = {
  page: 1,
  size: 10,
  total: 0
}
let userId = ''
const App = () => {
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (sex) => {
        if (sex == 0) {
          return <Tag color="gold">男</Tag>
        } else {
          return <Tag color="gold">女</Tag>
        }
      }
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '客服编号',
      dataIndex: 'customerService',
      key: 'customerService'
    },
    // {
    //   title: '机长代码',
    //   dataIndex: 'code',
    //   key: 'code'
    // },
    {
      title: '权限',
      key: 'identiy',
      dataIndex: 'identiy',
      render: (identiy) => {
        if (identiy == 0) {
          return <Tag color="green">超级管理员</Tag>
        } else {
          return <Tag color="green">普通用户</Tag>
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            disabled={data.identiy == 0 ? true : false}
            onClick={() => {
              showModalAdd(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              userDeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button
              disabled={data.identiy == 0 ? true : false}
              type="primary"
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getAppList()
    getUserList()
    getCodeList()
  }, [])
  let [isAddModalOpen, setIsAddModalOpen] = useState(false)
  let [optionsApp, setoptionsApp] = useState([])
  let [tableData, setTableData] = useState([])
  let [codeList, setcodeList] = useState([])
  const [form] = Form.useForm()
  // 获取app列表
  const getAppList = async () => {
    const res = await appList()
    setoptionsApp(
      res.data.res.map((item) => {
        return {
          label: item.name,
          value: item._id
        }
      })
    )
  }
  const getCodeList = async () => {
    let res = await numberList({ size: 10000, page: 1 })
    console.log(res.data.res)
    setcodeList(
      res.data.res.map((item) => {
        return {
          label: item.code,
          value: item.code
        }
      })
    )
  }
  // 获取用户列表
  const getUserList = async () => {
    let res = await userList({ pageData })
    let list = res.data.res
    setTableData(
      list.map((item) => {
        return {
          key: item._id,
          ...item,
          appid: JSON.parse(item.appid)
        }
      })
    )
    pageData.total = res.data.total
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getUserList()
  }
  const showModalAdd = (value) => {
    if (value._id) {
      let data = JSON.parse(JSON.stringify(value))
      // data.appid = data.appid.split(',')
      form.setFieldsValue(data)
      userId = data._id
    }
    setIsAddModalOpen(true)
  }
  const onFinish = async (values) => {
    if (!userId) {
      if (values.imageurl) {
        values.imageurl = values.imageurl.fileList[0].response.image_url
        try {
          const data = await useradminadd(values)
          messageApi.success(data.data.res)
          setIsAddModalOpen(false)
          getUserList()
          form.resetFields()
        } catch (error) {
          messageApi.error(error.response.data.message.res)
        }
      } else {
        messageApi.warning('请上传头像')
      }
    } else {
      values._id = userId
      const data = await useradminadd(values)
      messageApi.success(data.data.message)
      setIsAddModalOpen(false)
      getUserList()
      form.resetFields()
      userId = ''
    }
  }
  const onFinishFailed = (errorInfo) => {
    console.log(errorInfo)
  }
  // 删除用户
  const userDeleteFn = async (data) => {
    await userdelete({ _id: data._id })
    message.success('删除成功')
    getUserList()
  }
  const cancelFn = () => {
    setIsAddModalOpen(false)
    form.resetFields()
    userId = ''
  }
  return (
    <div>
      <Button className="addbutton" type="primary" onClick={showModalAdd}>
        添加用户
      </Button>
      <Table
        columns={columns}
        dataSource={tableData}
        bordered
        pagination={false}
      />
      <div className="Pagin">
        <Pagination
          onChange={pageChangeFn}
          defaultCurrent={pageData.page}
          total={pageData.total}
        />
      </div>
      <Modal
        title="添加用户"
        open={isAddModalOpen}
        footer={[]}
        onCancel={() => {
          setIsAddModalOpen(false)
        }}
      >
        <Form
          labelCol={{
            span: 5
          }}
          wrapperCol={{
            span: 14
          }}
          layout="horizontal"
          style={{
            maxWidth: 800
          }}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="姓名"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入姓名'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="性别" name="sex">
            <Radio.Group>
              <Radio value="0"> 男 </Radio>
              <Radio value="1"> 女 </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="客服编号"
            name="customerService"
            rules={[
              {
                required: true,
                message: '请输入客服编号'
              }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              {
                required: true,
                message: '请输入手机号'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="选择小程序"
            name="appid"
            rules={[
              {
                required: true,
                message: '请选择'
              }
            ]}
          >
            <Select
              mode="multiple"
              allowClear
              style={{
                width: '100%'
              }}
              placeholder="请选择"
              options={optionsApp}
            />
          </Form.Item>
          <Form.Item label="头像" name="imageurl">
            <Upload
              maxCount={1}
              action={baseURL + 'api/uploadAvatar'}
              listType="picture-card"
            >
              <button
                style={{
                  border: 0,
                  background: 'none'
                }}
                type="button"
              >
                <PlusOutlined />
                <div
                  style={{
                    marginTop: 8
                  }}
                ></div>
              </button>
            </Upload>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 6,
              span: 16
            }}
          >
            <Button type="primary" htmlType="submit">
              确定
            </Button>
            <Button
              style={{ marginLeft: '10px' }}
              type="primary"
              onClick={cancelFn}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </div>
  )
}
export default App
